"""Robot类 - RPA框架的核心控制中心"""

import time
import traceback
from typing import List, Dict, Any, Optional

from rpa_framework.rpa_logging.logger import Logger
from rpa_framework.exceptions.rpa_exceptions import TimeoutException, RobotExecutionException
from rpa_framework.config.config_manager import ConfigManager

class Robot:
    """RPA机器人核心类，负责协调和执行自动化任务"""
    
    def __init__(self, config_path: str = None, name: str = None, description: str = None,
                 retry_count: int = 3, retry_interval: float = 1.0, default_timeout: int = 300):
        """初始化机器人
        
        Args:
            config_path: 配置文件路径
            name: 机器人名称
            description: 机器人描述
            retry_count: 默认重试次数
            retry_interval: 默认重试间隔（秒）
            default_timeout: 默认超时时间（秒）
        """
        self.logger = Logger()
        self.config_manager = ConfigManager(config_path)
        self.tasks_executed = 0
        self.tasks_failed = 0
        self.is_running = False
        self.start_time = None
        self.end_time = None
        # 添加新属性
        self.name = name or "RPA机器人"
        self.description = description or "自动化任务执行机器人"
        self.retry_count = retry_count
        self.retry_interval = retry_interval
        self.default_timeout = default_timeout
    
    @property
    def run_time(self):
        """获取机器人运行时间（秒）"""
        if self.is_running and self.start_time:
            return time.time() - self.start_time
        return 0
    
    @property
    def status(self):
        """获取机器人状态"""
        return "运行中" if self.is_running else "已停止"
    
    @property
    def executed_tasks_count(self):
        """已执行任务数"""
        return self.tasks_executed
    
    @property
    def successful_tasks_count(self):
        """成功任务数"""
        return self.tasks_executed - self.tasks_failed
    
    @property
    def failed_tasks_count(self):
        """失败任务数"""
        return self.tasks_failed
    
    def start(self) -> None:
        """启动机器人"""
        self.logger.info("机器人启动中...")
        self.is_running = True
        self.start_time = time.time()
        self.logger.info(f"机器人已启动，时间: {time.strftime('%Y-%m-%d %H:%M:%S')}")
    
    def stop(self) -> None:
        """停止机器人"""
        self.is_running = False
        self.end_time = time.time()
        duration = self.end_time - self.start_time
        
        summary = {
            "总任务数": self.tasks_executed,
            "失败任务数": self.tasks_failed,
            "成功任务数": self.tasks_executed - self.tasks_failed,
            "运行时长": f"{duration:.2f}秒"
        }
        
        self.logger.info("机器人停止运行")
        self.logger.info(f"运行摘要: {summary}")
    
    def execute_task(self, task_func, *args, **kwargs) -> Any:
        """执行单个任务
        
        Args:
            task_func: 要执行的任务函数
            *args: 位置参数
            **kwargs: 关键字参数
            
        Returns:
            任务函数的返回值
            
        Raises:
            RPAExecutionException: 任务执行失败时抛出
        """
        self.tasks_executed += 1
        task_name = task_func.__name__
        
        self.logger.info(f"开始执行任务: {task_name}")
        
        try:
            result = task_func(*args, **kwargs)
            self.logger.info(f"任务 {task_name} 执行成功")
            return result
            
        except Exception as e:
            self.tasks_failed += 1
            error_msg = f"任务 {task_name} 执行失败: {str(e)}"
            self.logger.error(error_msg)
            self.logger.debug(traceback.format_exc())
            raise RPAExecutionException(error_msg) from e
    
    def execute_workflow(self, workflow: List[Dict[str, Any]]) -> Dict[str, Any]:
        """执行工作流
        
        Args:
            workflow: 工作流定义，包含一系列任务
                      格式: [{"task": task_func, "args": [], "kwargs": {}, "name": "任务名称"}]
            
        Returns:
            包含各任务执行结果的字典
        """
        self.logger.info(f"开始执行工作流，共 {len(workflow)} 个任务")
        results = {}
        
        for idx, task_config in enumerate(workflow):
            task_func = task_config.get("task")
            args = task_config.get("args", [])
            kwargs = task_config.get("kwargs", {})
            task_name = task_config.get("name", f"任务_{idx+1}")
            
            try:
                results[task_name] = self.execute_task(task_func, *args, **kwargs)
            except RPAExecutionException:
                # 记录失败但继续执行后续任务
                results[task_name] = None
                self.logger.warning(f"工作流继续执行，忽略失败的任务: {task_name}")
        
        self.logger.info("工作流执行完成")
        return results
    
    def wait(self, seconds: int or float) -> None:
        """等待指定时间
        
        Args:
            seconds: 等待时间（秒）
        """
        self.logger.debug(f"等待 {seconds} 秒")
        time.sleep(seconds)
    
    def retry(self, task_func, max_retries: int = 3, delay: int = 2, *args, **kwargs) -> Any:
        """重试执行任务
        
        Args:
            task_func: 要执行的任务函数
            max_retries: 最大重试次数
            delay: 重试间隔（秒）
            *args: 位置参数
            **kwargs: 关键字参数
            
        Returns:
            任务函数的返回值
        """
        retries = 0
        last_exception = None
        
        while retries <= max_retries:
            try:
                return task_func(*args, **kwargs)
            except Exception as e:
                last_exception = e
                retries += 1
                
                if retries <= max_retries:
                    self.logger.warning(f"任务执行失败，{delay}秒后重试 ({retries}/{max_retries})")
                    self.wait(delay)
                else:
                    self.logger.error(f"任务执行失败，已达最大重试次数 {max_retries}")
        
        raise last_exception
    
    def get_status(self) -> Dict[str, Any]:
        """获取机器人状态
        
        Returns:
            包含机器人状态信息的字典
        """
        return {
            "运行状态": "运行中" if self.is_running else "已停止",
            "已执行任务数": self.tasks_executed,
            "失败任务数": self.tasks_failed,
            "启动时间": time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(self.start_time)) if self.start_time else None,
            "运行时长": f"{(time.time() - self.start_time):.2f}秒" if self.is_running and self.start_time else None
        }

if __name__ == "__main__":
    # 示例用法
    robot = Robot()
    robot.start()
    
    def example_task(name):
        return f"Hello, {name}!"
    
    result = robot.execute_task(example_task, "RPA")
    print(result)
    
    robot.stop()